﻿using System;
using System.Collections.Generic;
using System.Text;
using WLMCoreLibrary;
using System.Xml;
using System.Configuration;
using System.Web;
using System.IO;
using System.Web.UI;
using System.Data.Odbc;
using System.Text.RegularExpressions;
using System.Xml.XPath;
using System.Net;

namespace MiWebSite_Core
{
    public static class MiWebSiteFunctions
    {

        public static XmlDocument LoadFrontPageXML(string xmlUrl)
        {
            XmlDocument salida = new XmlDocument();
            XmlDocument documento = new XmlDocument();
            documento.Load(xmlUrl);
            XPathNavigator navigator = documento.CreateNavigator();
            XPathExpression selectExpression = navigator.Compile("WebSiteModules/module");
            XPathExpression sortExpr = navigator.Compile("position");
            selectExpression.AddSort(sortExpr, new OrderComparer());
            XPathNodeIterator nodeList = navigator.Select(selectExpression);
            while (nodeList.MoveNext())
            {
                List<ParametroTransformacionXML> parametros = new List<ParametroTransformacionXML>();
                parametros.Add(new ParametroTransformacionXML("totalElementos", nodeList.Current.SelectSingleNode("pageItems").Value));
                //string xml = "<div>" +
                //    WLMFunctions.TransformXML(
                //        nodeList.Current.SelectSingleNode("DataURL").Value,
                //        nodeList.Current.SelectSingleNode("TransformURL").Value,
                //        parametros
                //        ) +
                //    "</div>";
                XmlDocument docconte = new XmlDocument();
                docconte.Load(nodeList.Current.SelectSingleNode("DataURL").Value);
                salida.AppendChild(docconte.SelectSingleNode(nodeList.Current.SelectSingleNode("TransformURL").Value));
            }
            return salida;
        }

        //public static string CambiosPlantilla(string original,ref dbConnector conexion)
        //{
        //    original = original.Replace("[NOMBREWEBSITE]", CurrentDomain.DomainName);
        //    if (original.Contains("[ROBAPAGINAS]"))
        //        original = original.Replace("[ROBAPAGINAS]", ShowBanner(2));
        //    if (original.Contains("[BANNER]"))
        //        original = original.Replace("[BANNER]", ShowBanner(3));
        //    if (original.Contains("[SUPERBANNER]"))
        //        original = original.Replace("[SUPERBANNER]", ShowBanner(1));
        //    if (original.Contains("[SKYCRAPPER]"))
        //        original = original.Replace("[SKYCRAPPER]", ShowBanner(4));
           
        //    //if (original.Contains("[NOTICIASPORTADA]"))
        //    return original;
        //}

        //public static string ShowBanner(int tipo)
        //{
        //    string banner = "";
        //    switch (tipo)
        //    {
        //        case 1: //728*90
        //            banner = "<iframe src='URL/banners.aspx?tipo=1' frameborder='0' width='728' height='90' scrolling='no'></iframe>";
        //            break;
        //        case 2: //250*250
        //            banner = "<iframe src='URL/banners.aspx?tipo=2' frameborder='0' width='250' height='250' scrolling='no'></iframe>";
        //            break;
        //        case 3: //468*60
        //            banner = "<iframe src='URL/banners.aspx?tipo=3' frameborder='0' width='468' height='60' scrolling='no'></iframe>";
        //            break;
        //        case 4: //200*200
        //            banner = "<iframe src='URL/banners.aspx?tipo=4' frameborder='0' width='160' height='600' scrolling='no'></iframe>";
        //            break;
        //        case 5: //120*600
        //            banner = "<iframe src='URL/banners.aspx?tipo=5' frameborder='0' width='120' height='600' scrolling='no'></iframe>";
        //            break;
        //    }
        //    return banner;
        //}


        //public static string LoadTemplate(string fileName)
        //{
        //    string skinSource = "";

        //    if (HttpContext.Current.Application[fileName] == null || HttpContext.Current.IsDebuggingEnabled)
        //    {
        //        string skinPath = ConfigurationManager.AppSettings["skinPath"];
        //        string siteURL = ConfigurationManager.AppSettings["MainSiteURL"];
        //        string sitePath = ConfigurationManager.AppSettings["SitePath"];
        //        try
        //        {

        //            TextReader fileReader = new StreamReader(sitePath + "/" + skinPath + fileName);
        //            skinSource = fileReader.ReadToEnd();
        //            fileReader.Close();
        //        }
        //        catch (Exception ex)
        //        {
        //            //HttpContext.Current.Response.Write("Plantilla " + fileName + " no encontrada, intente mas tarde");
        //            TextReader fileReader = new StreamReader(sitePath + "/GlobalTemplates/" + fileName);
        //            skinSource = fileReader.ReadToEnd();
        //            fileReader.Close();
        //        }
        //        finally
        //        {
        //            if (skinSource.Contains("{URL}"))
        //                skinSource = skinSource.Replace("{URL}", siteURL);
        //            if (skinSource.Contains("{RUTA}"))
        //                skinSource = skinSource.Replace("{RUTA}", siteURL + skinPath);

        //            HttpContext.Current.Application.Add(fileName, skinSource);
        //        }
        //    }
        //    else
        //        skinSource = HttpContext.Current.Application[fileName].ToString();


        //    return skinSource;
        //}

        //public static MiWebSiteCurrentDomain getSubDomain(dbConnector conexion)
        //{


        //    MiWebSiteCurrentDomain dominioActual = new MiWebSiteCurrentDomain(conexion);
        //    return dominioActual;
        //}


        //public static string PonerCalendario(string idCalendario, DateTime fechaInicial)
        //{
        //    string salida;
        //    //if (calendarios==0)
        //    //{

        //    //calendarios=1

        //    //}
        //    //if cstr(fechaInicial)="0" then
        //    //    fechaInicial=cstr(date)
        //    //end if

        //    salida = "<img id=\"boton2" + idCalendario + "\" src='" + ConfigurationManager.AppSettings["MainsiteURL"] + "/calendar/cal.gif' onMouseOver=\"inicializarCalendario('" + idCalendario + "','boton2" + idCalendario + "','" + fechaInicial.ToString("dd/MM/yyyyyy") + "','parent');\">";
        //    return salida;
        //}

        //public static string CrearMenuInferior(int categoria, int profundidad, string MenuName, string catBehind, ref dbConnector ConexionDB)
        //{
        //    string strCommand;
        //    string cadena;
        //    int x;
        //    bool hijos = false;
        //    StringBuilder salida = new StringBuilder();
        //    if (HttpContext.Current.Application["MenuInferior"] == null || CurrentUser.NivelUsuario > 5)
        //    {
        //        strCommand = "SELECT categorias.*,imagenes.archivo as imagen from categorias left join imagenes on imagenes.id=categorias.idImagen WHERE idPadre=" + categoria + " ORDER BY orden";

        //        OdbcDataReader registro = dbConn.ExecuteReader(strCommand);
        //        if (profundidad == 0)
        //            salida.Append("<ul>\n");
        //        while (registro.Read())
        //        {
        //            string catName = tituloaPostName(registro["nombre"].ToString());
        //            if (Convert.ToString(registro["url"]) != "")
        //            {
        //                if (Convert.ToString(registro["imagen"]) != "")
        //                    salida.Append("<li><a href=\"#\">" + registro["nombre"] + "</a>\n");
        //                else
        //                {
        //                    if (profundidad == 0)
        //                        salida.Append("<li><a href=\"" + registro["url"] + "\">" + registro["nombre"] + "</a>\n");
        //                    else
        //                        salida.Append("<li><a href=\"" + registro["url"] + "\">" + registro["nombre"] + "</a>\n");

        //                }
        //            }
        //            else
        //            {
        //                if (Convert.ToString(registro["imagen"]) != "")
        //                    salida.Append("<li><a href=\"/" + catBehind + catName + "/\"><span>" + registro["nombre"] + "</span></a>");
        //                else
        //                {
        //                    if (profundidad == 0)
        //                        salida.Append("<li><a href=\"/" + catBehind + catName.ToLower() + "/\">" + registro["nombre"] + "</a>");
        //                    else
        //                        salida.Append("<li><a href=\"/" + catBehind + catName.ToLower() + "/\">" + registro["nombre"] + "</a>");

        //                }
        //            }
        //            salida.Append("</li>\n");
        //        }


        //        if (profundidad == 0)
        //            if (CurrentUser.NivelUsuario >= 5)
        //                salida.Append("<li><a href='/login/?logout=1'>logout</a></li></ul>\n");
        //            else
        //                salida.Append("<li><a href='/login/'>&pi;</a></li></ul>\n");
        //        registro = null;
        //        if (profundidad == 0)
        //            HttpContext.Current.Application["MenuInferior"] = salida.ToString();
        //        return salida.ToString();
        //    }
        //    else
        //        return HttpContext.Current.Application["MenuInferior"].ToString();
        //}

        //public static string CrearMenuSuperior(int categoria, int profundidad, string MenuName, string catBehind, ref dbConnector ConexionDB)
        //{
        //    string strCommand;
        //    bool hijos = false;
        //    StringBuilder salida = new StringBuilder();

        //    if (HttpContext.Current.Application["MenuPrincipal"] == null)// || CurrentUser.NivelUsuario > 5)
        //    {
        //        strCommand = "SELECT categorias.*,imagenes.archivo as imagen from categorias left join imagenes on imagenes.id=categorias.idImagen WHERE idPadre=" + categoria + " ORDER BY categorias.orden";

        //        OdbcDataReader registro = dbConn.ExecuteReader(strCommand);

        //        if (registro.HasRows)// || CurrentUser.NivelUsuario > 5)
        //        {
        //            hijos = true;
        //            if (profundidad != 0)
        //                salida.Append("<ul id=\"" + categoria + "-hijos\" class=\"menuChildNode\">\n");
        //        }
        //        int contadorReg = 0;
        //        int totalOpciones = registro.RecordsAffected;
        //        while (registro.Read())
        //        {
        //            string catName = tituloaPostName(registro["nombre"].ToString());

        //            //if (CurrentUser.NivelUsuario > 5)
        //            //{
        //            //    if (Convert.ToString(registro["url"]) != "")
        //            //    {
        //            //        salida.Append("<li id='" + registro["id"] + "'><a href=\"" + registro["url"] + "\" rel='"+registro["orden"]+"'><span>" + registro["nombre"] + "</span></a>\n");

        //            //    }
        //            //    else
        //            //    {
        //            //        salida.Append("<li id='" + registro["id"] + "'>" +
        //            //            "<span>"+// id='" + registro["id"] + "-editor'>" +
        //            //            "<a href='/" + catBehind + catName.ToLower() + "/' rel='" + registro["orden"] + "'>" +
        //            //             registro["nombre"] + "</a>" +
        //            //             " </span>");

        //            //    }
        //            //}
        //            //else
        //            {
        //                if (profundidad == 0 && contadorReg == 0)
        //                    salida.Append("<li class='inicioMenu' id='" + registro["id"] + "'>");
        //                else
        //                    if (profundidad == 0 && contadorReg == totalOpciones - 1)
        //                        salida.Append("<li class='finalMenu' id='" + registro["id"] + "'>");
        //                    else
        //                        salida.Append("<li id='" + registro["id"] + "'>");
        //                if (Convert.ToString(registro["url"]) != "")
        //                {
        //                    salida.Append("<a href=\"" + registro["url"] + "\" rel='" + registro["orden"] + "'><span>" + registro["nombre"] + "</span></a>\n");

        //                }
        //                else
        //                {
        //                    salida.Append("<a href=\"/" + catBehind + catName.ToLower() + "/\" rel='" + registro["orden"] + "'><span>" + registro["nombre"] + "</span></a>");
        //                }
        //            }

        //            salida.Append(CrearMenuSuperior(Convert.ToInt32(registro["id"]), profundidad + 1, MenuName, catBehind + catName + "/", dbConn));
        //            salida.Append("</li>\n");
        //            contadorReg++;
        //        }

        //        if (hijos && profundidad != 0)
        //        {
        //            salida.Append("</ul>");
        //        }


        //        registro = null;
        //        if (profundidad == 0)// && CurrentUser.NivelUsuario <= 5)
        //        {
        //            HttpContext.Current.Application["MenuPrincipal"] = salida.ToString();

        //        }
        //        else
        //            if (profundidad != 0)
        //                return salida.ToString();

        //    }
        //    if (MenuName != "")
        //        return "<ul id=\"" + MenuName + "\" >\n" + HttpContext.Current.Application["MenuPrincipal"].ToString() + "</ul>\n";
        //    else
        //        return HttpContext.Current.Application["MenuPrincipal"].ToString();

        //}


        //StringBuilder menuAdministrativo = new StringBuilder();
        //    if (profundidad == 0 && CurrentUser.NivelUsuario > 5)
        //    {
        //        menuAdministrativo.Append("<li><a href=\"#\"><span>Administracion</span></a><ul class=\"menuChildNode\">");
        //        MiWebSiteModulesCollection modulos = new MiWebSiteModulesCollection(CurrentUser.NivelUsuario, dbConn);
        //        foreach (MiWebSiteModules modulo in modulos.ModulesList)
        //        {
        //            menuAdministrativo.Append("<li><a href=\"" + modulo.URLAdmin + "\"><span>" + modulo.Nombre + "</span></a></li>");

        //        }
        //        menuAdministrativo.Append("</ul></li>");
        //        return "<ul id=\"" + MenuName + "\" >\n" + salida.ToString() + menuAdministrativo.ToString() + "</ul>\n" +
        //            "<script type='text/javascript'>\n"
        //            + "function CargarEditorMenu(idNodo){\n"
        //            + "var ContenidoEditor = $('#PlantillaMenuEditor').html();\n"
        //            + "ContenidoEditor=ContenidoEditor.replace(/IDMENU/gi,idNodo);\n"
        //            + "ContenidoEditor=ContenidoEditor.replace(/VALORMENU/gi,$('#'+idNodo+'-editor').text().replace(/^\\s*|\\s*$/g,''));\n"
        //            + "$('#'+idNodo+'-editor').html(ContenidoEditor);\n"
        //            + "}         \n\n\n\n     "
        //            + "function BorrarMenu(idNodo){\n"
        //            + "var confirmacion= confirm(\"Esta seguro de querer borrar la opcion de menu '\"+ $('#'+idNodo+'-editor').text() + \"' ?\\nEsto eliminara tambien todos los submenus que le pertenescan.\");\n"
        //            + "if(confirmacion){$('#'+idNodo+'-editor').load('/handlers/MenuHandler.ashx?idOpcionBorrar='+idNodo);\n"
        //            + "$('#'+idNodo+'-borrado').remove();\n"
        //            + "}}\n\n\n\n        "
        //            + "function ActualizarOpcionMenu(idOpcionMenu){\n"
        //            + "var NombreMenu=$('#'+idOpcionMenu+'-nuevo').val();\n"
        //            + "if(NombreMenu!=''){NombreMenu=NombreMenu.replace(/ /gi,'_');\n"
        //            + "var DireccionMenu='/handlers/MenuHandler.ashx?nombreOpcion='+NombreMenu+'&idOpcion='+idOpcionMenu;$('#'+idOpcionMenu+'-editor').load(DireccionMenu);\n"
        //            + "}}         \n\n\n  "
        //            + "function CrearOpcionMenu(idPadre){\n"
        //            + "var NombreMenu=$('#'+idPadre+'-nuevo').val();\n"
        //            + "var contenido=$('#PlantillaMenuNuevo').html();"
        //            + "if(NombreMenu!=''){\n"
        //            + "     var numRand = Math.floor(Math.random()*401);\n"
        //            + "     $('#'+idPadre+'-contenedor').attr('id','Cargador'+numRand);\n"
        //            + "     NombreMenu=NombreMenu.replace(/ /gi,'_');\n"
        //            + "     var DireccionMenu='/handlers/MenuHandler.ashx?nombreOpcion='+NombreMenu+'&idOpcionPadre='+idPadre;\n"
        //            + "     $('#Cargador'+numRand).load(DireccionMenu);\n"
        //            + "     contenido=contenido.replace(/IDMENU/gi,idPadre);\n"
        //            + "     $('#'+idPadre+'-hijos').append('<li id=\"'+idPadre+'-contenedor\">'+contenido+'</li>');"
        //            + "     }"
        //            + "}\n"
        //            + "\n\n"
        //            + "</script>\n"
        //            + "<div id='PlantillaMenuEditor' style='display:none;'><a href='javascript:void();' >\n"
        //            + "<span><input style='font-size:11px; width:70px;' type='text' id='IDMENU-nuevo' name='IDMENU-nuevo' value='VALORMENU'/>\n "
        //            + "<img src='/iconos/accept.png' border='0' align='absmiddle' onclick=\"ActualizarOpcionMenu(IDMENU);\"/></span></a>\n</div>\n"
        //            + "<div id='PlantillaMenuNuevo' style='display:none;'><input style='font-size:11px; width:70px;' type='text' id='IDMENU-nuevo' name='IDMENU-nuevo'/> <img src='/iconos/add.png' border='0' align='absmiddle' onclick=\"CrearOpcionMenu(IDMENU);\"/></div>";

        //    }
        //    else

        public static bool isMobileBrowser()
        {
            //GETS THE CURRENT USER CONTEXT
            HttpContext context = HttpContext.Current;

            //FIRST TRY BUILT IN ASP.NT CHECK
            if (context.Request.Browser.IsMobileDevice)
            {
                return true;
            }
            //THEN TRY CHECKING FOR THE HTTP_X_WAP_PROFILE HEADER
            if (context.Request.ServerVariables["HTTP_X_WAP_PROFILE"] != null)
            {
                return true;
            }
            //THEN TRY CHECKING THAT HTTP_ACCEPT EXISTS AND CONTAINS WAP
            if (context.Request.ServerVariables["HTTP_ACCEPT"] != null &&
                context.Request.ServerVariables["HTTP_ACCEPT"].ToLower().Contains("wap"))
            {
                return true;
            }
            //AND FINALLY CHECK THE HTTP_USER_AGENT 
            //HEADER VARIABLE FOR ANY ONE OF THE FOLLOWING
            if (context.Request.ServerVariables["HTTP_USER_AGENT"] != null)
            {
                //Create a list of all mobile types
                string[] mobiles =
                    new[]
                {
                    "midp", "j2me", "avant", "docomo", 
                    "novarra", "palmos", "palmsource", 
                    "240x320", "opwv", "chtml",
                    "pda", "windows ce", "mmp/", 
                    "blackberry", "mib/", "symbian", 
                    "wireless", "nokia", "hand", "mobi",
                    "phone", "cdm", "up.b", "audio", 
                    "SIE-", "SEC-", "samsung", "HTC", 
                    "mot-", "mitsu", "sagem", "sony"
                    , "alcatel", "lg", "eric", "vx", 
                    "NEC", "philips", "mmm", "xx", 
                    "panasonic", "sharp", "wap", "sch",
                    "rover", "pocket", "benq", "java", 
                    "pt", "pg", "vox", "amoi", 
                    "bird", "compal", "kg", "voda",
                    "sany", "kdd", "dbt", "sendo", 
                    "sgh", "gradi", "jb", "dddi", 
                    "moto", "iphone","webos","android"
                };

                //Loop through each item in the list created above 
                //and check if the header contains that text
                foreach (string s in mobiles)
                {
                    if (context.Request.ServerVariables["HTTP_USER_AGENT"].
                                                        ToLower().Contains(s.ToLower()))
                    {
                        return true;
                    }
                }
            }

            return false;
        }

        public static string tituloaPostName(string titulo)
        {
            string salida = titulo.Trim().Replace(" ", "-").Replace("_", "-").Replace(".", "").Replace("?", "").Replace("¿", "").Replace("!", "").Replace("¡", "").Replace(",", "").Replace(":", "").Replace(";", "").Replace("(", "").Replace(")", "").Replace("/", "").Replace("#", "").Replace("'", "").Replace("\"", "").Replace("á", "a").Replace("é", "e").Replace("í", "i").Replace("ó", "o").Replace("ú", "u").Replace("~", "").Replace("ñ", "n").Replace("|", "").Replace("°", "").Replace("@", "a").Replace("ü", "u").Replace("ï", "i").Replace("ä", "a").Replace("ë", "e").Replace("ö", "o").Replace("[", "").Replace("]", "").Replace("{", "").Replace("}", "").Replace("%", "").Replace("$", "").Replace("&", "").Replace("/", "").Replace("^", "").Replace("`", "").ToLower().Replace("--------", "-").Replace("------", "-").Replace("----", "-").Replace("--", "-");
            if(salida.Length>0)
            if (salida[salida.Length - 1] == '-')
                salida = salida.Substring(0, salida.Length - 1);
            return salida;
        }

        public static string cleanContentName(string titulo)
        {
            return titulo.Trim().Replace(" ", "-").Replace("_", "-").Replace(".", "").Replace("?", "").Replace("¿", "").Replace("!", "").Replace("¡", "").Replace(",", "").Replace(":", "").Replace(";", "").Replace("(", "").Replace(")", "").Replace("#", "").Replace("'", "").Replace("\"", "").Replace("á", "a").Replace("é", "e").Replace("í", "i").Replace("ó", "o").Replace("ú", "u").Replace("~", "").Replace("ñ", "n").Replace("|", "").Replace("°", "").Replace("@", "a").Replace("ü", "u").Replace("ï", "i").Replace("ä", "a").Replace("ë", "e").Replace("ö", "o").Replace("[", "").Replace("]", "").Replace("{", "").Replace("}", "").Replace("%", "").Replace("$", "").Replace("&", "").Replace("^", "").Replace("`", "").ToLower().Replace("--", "-");
        }

        //public static string ListaLateral(int categoria, int profundidad, string MenuName, string catBehind, ref dbConnector ConexionDB)
        //{
        //    string strCommand;
        //    string cadena;
        //    int x;
        //    bool hijos = false;
        //    StringBuilder salida = new StringBuilder();

        //    if (HttpContext.Current.Application[MenuName] == null || CurrentUser.NivelUsuario > 5)
        //    {
        //        strCommand = "SELECT categorias.*,imagenes.archivo as imagen from categorias left join imagenes on imagenes.id=categorias.idImagen WHERE idPadre=" + categoria + " ORDER BY orden";

        //        OdbcDataReader registro = dbConn.ExecuteReader(strCommand);
        //        if (profundidad == 0)
        //            salida.Append("<ul id='" + MenuName + "' class='SideMenuClass'>\n");
        //        while (registro.Read())
        //        {
        //            string catName = tituloaPostName(registro["nombre"].ToString());
        //            if (CurrentUser.NivelUsuario > 5)
        //            {
        //                if (Convert.ToString(registro["url"]) != "")
        //                {
        //                    salida.Append("<li><a href=\"" + registro["url"] + "\"><span>" + registro["nombre"] + "</span></a>\n");
        //                }
        //                else
        //                {
        //                    salida.Append("<li id='" + registro["id"] + "-borrado'><span id='" + registro["id"] + "-editor'><a href='javascript:void();' ondblclick=\"location.href='/" + catBehind + catName.ToLower() + "/';\"><span>" + registro["nombre"] + "</span> <img src='/iconos/pencil.png' border='0' align='absmiddle' onclick=\"CargarEditorMenu(" + registro["id"] + ");\"/> <img src='/iconos/delete.png'border='0' align='absmiddle' onclick=\"BorrarMenu(" + registro["id"] + ");\"/></a></span>");
        //                }
        //            }
        //            else
        //                if (Convert.ToString(registro["url"]) != "")
        //                {
        //                    if (Convert.ToString(registro["imagen"]) != "")
        //                        salida.Append("<li><a href=\"#\">" + registro["nombre"] + "</a>\n");
        //                    else
        //                    {
        //                        if (profundidad == 0)
        //                            salida.Append("<li><a href=\"" + registro["url"] + "\">" + registro["nombre"] + "</a>\n");
        //                        else
        //                            salida.Append("<li><a href=\"" + registro["url"] + "\">" + registro["nombre"] + "</a>\n");

        //                    }
        //                }
        //                else
        //                {
        //                    if (Convert.ToString(registro["imagen"]) != "")
        //                        salida.Append("<li><a href=\"/" + catBehind + catName + "/\"><span>" + registro["nombre"] + "</span></a>");
        //                    else
        //                    {
        //                        if (profundidad == 0)
        //                            salida.Append("<li><a href=\"/" + catBehind + catName.ToLower() + "/\">" + registro["nombre"] + "</a>");
        //                        else
        //                            salida.Append("<li><a href=\"/" + catBehind + catName.ToLower() + "/\">" + registro["nombre"] + "</a>");

        //                    }
        //                }

        //            //salida.Append(ListaLateral(Convert.ToInt32(registro["id"]), profundidad + 1, MenuName, catBehind + catName + "/", dbConn));


        //            salida.Append("</li>\n");

        //        }


        //        if (CurrentUser.NivelUsuario > 5)
        //        {
        //            salida.Append("\n<li id='" + categoria + "-contenedor'><a href='javascript:void();' ><input style='font-size:11px; width:70px;' type='text' id='" + categoria + "-nuevo' name='" + categoria + "-nuevo'/> <img src='/iconos/add.png' border='0' align='absmiddle' onclick=\"CrearOpcionMenu(" + categoria + ");\"/></a></li>");



        //        }





        //        if (profundidad == 0)
        //            salida.Append("</ul>\n");
        //        registro = null;
        //        if (profundidad == 0)
        //            HttpContext.Current.Application[MenuName] = salida.ToString();
        //        return salida.ToString();
        //    }
        //    else
        //        return HttpContext.Current.Application[MenuName].ToString();
        //}


        public static int BuscarRegistro(string tabla, string campo, string valor,ref dbConnector ConexionDB)
        {
            string strCommand;
            int idRegistro;
            strCommand = "SELECT * FROM " + tabla + " WHERE " + campo + "='" + valor + "' ORDER BY id DESC";
            OdbcDataReader reader = ConexionDB.ExecuteReader(strCommand);
            if (reader.HasRows)
                idRegistro = Convert.ToInt32(reader["id"]);
            else
                idRegistro = 0;
            return idRegistro;
        }



        ///// <summary>
        ///// Generate the page skin string based on filename
        ///// </summary>
        ///// <param name="fileName">Filename on skin</param>
        ///// <param name="isAdminPage">if true loads javascript needed for admin pages</param>
        ///// <returns>skin page string</returns>
        //public static string LoadTemplate(string fileName, string TituloAdicional, string AditionalKeywords,ref dbConnector MiWebSiteConnection)
        //{
        //    string skinPath = ConfigurationManager.AppSettings["skinPath"];
        //    string siteURL = ConfigurationManager.AppSettings["MainSiteURL"];
        //    string sitePath = ConfigurationManager.AppSettings["SitePath"];
        //    MiWebSiteCurrentDomain currenDomain = getSubDomain(MiWebSiteConnection);
        //    string siteDomain = currenDomain.dominio;
        //    string siteDomain2 = siteDomain.Substring(2);
        //    string DomainDescription = currenDomain.Description;
        //    string skinSource = "";

        //    if (HttpContext.Current.Application[fileName] == null || HttpContext.Current.IsDebuggingEnabled)
        //    {
        //        try
        //        {
        //            TextReader fileReader = new StreamReader(sitePath + "/" + skinPath + fileName);
        //            skinSource = fileReader.ReadToEnd();
        //            fileReader.Close();
        //            HttpContext.Current.Application.Add(fileName, skinSource);
        //        }
        //        catch (Exception ex)
        //        {
        //            HttpContext.Current.Response.Write("Plantilla " + fileName + " no encontrada, intente mas tarde");
        //        }
        //    }
        //    else
        //        skinSource = HttpContext.Current.Application[fileName].ToString();


        //    //Carga las librerias de Jquery de forma remota si esta en produccion o localmente si esta en modo debug
        //    string jqueryURL = "<script language=\"javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js\"> </script> \n" +
        //        "<script language=\"javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js\"> </script>\n";
        //    if (HttpContext.Current.IsDebuggingEnabled)
        //        jqueryURL = "<script language='javascript' src='/jquery/jquery.js'></script>\n" +
        //        "<script language='javascript' src='/jquery/jquery-ui.js'></script> ";
        //    string includesHead = jqueryURL +

        //        "<link href='/css/jquery-ui.css' rel='stylesheet' type='text/css' />" +
        //        "<script language='javascript' src='/jquery/jquery.droppy.js'></script>\n" +
        //        "<script language='javascript' src='/jquery/jquery.pngFix.js'></script>\n" +
        //        "<script language='javascript' src='/jquery/js.js'></script>\n" +
        //        "<script language='javascript' src='/jquery/MenuAdmin.js'></script>\n" +
        //        "<script type='text/javascript'>\n$(document).ready(function() {\n    $('#MainMenu').droppy();\n	$(document).pngFix(); \n  });\n</script> ";
        //    string includesBody = "";
        //    string menuPrincipal = CrearMenuSuperior(BuscarRegistro("categorias", "nombre", "mapa del sitio", MiWebSiteConnection), 0, "MainMenu", "", MiWebSiteConnection);
        //    string menuInferior = CrearMenuInferior(BuscarRegistro("categorias", "nombre", "mapa del sitio", MiWebSiteConnection), 0, "MenuBottom", "", MiWebSiteConnection);
        //    string MenuLateral1 = ListaLateral(BuscarRegistro("categorias", "nombre", "lateral1", MiWebSiteConnection), 0, "MenuLateral1", "", MiWebSiteConnection);
        //    string MenuLateral2 = ListaLateral(BuscarRegistro("categorias", "nombre", "lateral2", MiWebSiteConnection), 0, "MenuLateral2", "", MiWebSiteConnection); ;
        //    string MenuLateral3 = ListaLateral(BuscarRegistro("categorias", "nombre", "lateral3", MiWebSiteConnection), 0, "MenuLateral3", "", MiWebSiteConnection); ;
        //    string subMenus = Convert.ToString(HttpContext.Current.Application["subMenus"]);


        //    if (CurrentUser.UserName != "")
        //        skinSource = skinSource.Replace("[PANELUSUARIO]", "Bienvenido " + CurrentUser.UserName + " <a href='/panel/'>ir al panel de control</a>");
        //    else
        //        skinSource = skinSource.Replace("[PANELUSUARIO]", "");



        //    // includesHead = includesHead + "<script type='text/javascript' src='/includes/js/prototype.js'></script><script type='text/javascript' src='/includes/js/effects.js'></script><script type='text/javascript' src='/includes/js/scriptaculous.js'></script><script type='text/javascript' src='/includes/js/js.js'></script><link rel='stylesheet' href='/includes/css/cropper.css' /><link rel='stylesheet' href='/includes/css/calendar-system.css' /><script type='text/javascript' src='/includes/js/cropper.js'></script>";

        //    skinSource = skinSource.Replace("[INCLUDESHEAD]", includesHead);
        //    skinSource = skinSource.Replace("[INCLUDESBODY]", includesBody);
        //    if (TituloAdicional == "")
        //        skinSource = skinSource.Replace("[TITULOWEBSITE]", ConfigurationManager.AppSettings["tituloWebSite"]);
        //    else
        //        skinSource = skinSource.Replace("[TITULOWEBSITE]", ConfigurationManager.AppSettings["tituloWebSite"].ToString() + " - " + TituloAdicional);
        //    skinSource = skinSource.Replace("[MENUPRINCIPAL]", menuPrincipal);
        //    skinSource = skinSource.Replace("[SUBMENUS]", "");
        //    skinSource = skinSource.Replace("[MENUINFERIOR]", menuInferior);
        //    skinSource = skinSource.Replace("[MENULATERAL1]", MenuLateral1);
        //    skinSource = skinSource.Replace("[MENULATERAL2]", MenuLateral2);
        //    skinSource = skinSource.Replace("[MENULATERAL3]", MenuLateral3);
        //    skinSource = skinSource.Replace("[NOMBREDOMINIO]", siteDomain);
        //    skinSource = skinSource.Replace("[DESCRIPCION]", DomainDescription);
        //    skinSource = skinSource.Replace("[NOMBREDOMINIO2]", siteDomain2);
        //    skinSource = skinSource.Replace("[SUBDOMINIO]", currenDomain.subdominio + ".");
        //    skinSource = skinSource.Replace("[SLOGAN]", currenDomain.slogan);
        //    skinSource = skinSource.Replace("[ESTADISTICAS]", currenDomain.estadisticas);
        //    if (HttpContext.Current.Application["keywords"] == null)
        //        new MiWebSiteKeyWordCollection(MiWebSiteConnection).GenerarKeywordsApplication();
        //    skinSource = skinSource.Replace("[KEYWORDS]", currenDomain.KeyWords + HttpContext.Current.Application["keywords"] + AditionalKeywords);
        //    skinSource = skinSource.Replace("[DESCRIPCION]", currenDomain.Description);
        //    skinSource = skinSource.Replace("[GENERATOR]", "MiWebSite 5.0 Administrador de Contenidos y Blog, Copyright WebLogsMexico 2009");
        //    if (CurrentUser.Email != null)
        //        skinSource = skinSource.Replace("[USUARIOACTUAL]", CurrentUser.UserName + " - <a href='/login/?logout=1'>Cerrar Sesion</a>");
        //    else
        //        skinSource = skinSource.Replace("[USUARIOACTUAL]", "Invitado");
        //    skinSource = AplicarCambios(skinSource, MiWebSiteConnection);

        //    return skinSource;
        //}


        //public static string AplicarCambios(string original,ref dbConnector MiWebSiteConnection)
        //{
        //    string skinPath = ConfigurationManager.AppSettings["skinPath"];
        //    string siteURL = ConfigurationManager.AppSettings["SiteURL"];
        //    string MainsiteURL = ConfigurationManager.AppSettings["MainSiteURL"];
        //    string sitePath = ConfigurationManager.AppSettings["SitePath"];
        //    string MainsitePath = ConfigurationManager.AppSettings["MainSitePath"];
        //    //if (original.Contains("[NUBETAGS]"))
        //    //    original = original.Replace("[NUBETAGS]", NubeTags(MiWebSiteConnection));
        //    if (original.Contains("URL"))
        //        original = original.Replace("URL", siteURL);
        //    if (original.Contains("RUTA"))
        //        original = original.Replace("RUTA", siteURL + skinPath);
        //    if (original.Contains("href=\"css/"))
        //        original = original.Replace("href=\"css/", "href=\"" + siteURL + skinPath + "css/");
        //    if (original.Contains("src=\"images/"))
        //        original = original.Replace("src=\"images/", "src=\"" + siteURL + skinPath + "images/");
        //    if (original.Contains("src=\"js/"))
        //        original = original.Replace("src=\"js/", "src=\"" + siteURL + skinPath + "js/");


        //    return original;
        //}

        //public static string[] InitWebPage(ref dbConnector conexion, System.Web.UI.Page page)
        //{
        //    conexion.OpenConnection();
        //    string[] SKIN = null;
        //    MiWebSiteFunctions.DisablePageCaching(page);
        //    if (!page.IsPostBack)
        //    {
        //        string skin = LoadTemplate("index.htm", "", "",ref conexion);
        //        string[] separador = { "[CONTENIDOPRINCIPAL]" };
        //        SKIN = skin.Split(separador, StringSplitOptions.None);
        //    }
        //    else
        //    {
        //        SKIN = new string[2];
        //        SKIN[0] = "";
        //        SKIN[1] = "";
        //    }
        //    if (HttpContext.Current.Request.QueryString["ajax"] == "1")
        //    {
        //        SKIN = new string[2];
        //        SKIN[0] = "";
        //        SKIN[1] = "";
        //    }
        //    return SKIN;
        //}

        public static void GrantAccess(ref dbConnector ConexionDB)
        {
            string pagina, redireccion, strCommand, nivelUsuario;
            bool accessGranted = false;
            HttpCookie recordar = HttpContext.Current.Request.Cookies["rememberMe"];
            if (recordar != null)
                if (Convert.ToBoolean(recordar.Value) && HttpContext.Current.Session["idUsuario"] == null)
                {

                    ValidateUser(HttpContext.Current.Request.Cookies["email"].Value.ToString(), HttpContext.Current.Request.Cookies["password"].Value.ToString(), Convert.ToBoolean(HttpContext.Current.Request.Cookies["rememberMe"].Value), ref ConexionDB);
                }
            OdbcDataReader rsDatos;

            pagina = HttpContext.Current.Request.ServerVariables["URL"].ToString();
            HttpContext.Current.Session["accessDenied"] = pagina.ToString();
            HttpContext.Current.Session["pageRequired"] = HttpContext.Current.Request.ServerVariables["QUERY_STRING"];
            redireccion = "/login";
            //if (HttpContext.Current.Request.QueryString["ajax"] == "1")
            //{
            //    redireccion = redireccion + "?ajax=1&pagina=" + pagina;
            //}
            //else
            redireccion = redireccion + "?pagina=" + pagina;
            if (HttpContext.Current.Session["nivelUsuario"] == null)
            {
                HttpContext.Current.Session["nivelUsuario"] = "1";
                HttpContext.Current.Session["nivelPrecio"] = "1";
            }
            nivelUsuario = Convert.ToString(HttpContext.Current.Session["nivelUsuario"]);
            strCommand = "SELECT 1,modulos.id as idModulo FROM modulosPermisos join modulos on modulosPermisos.idModulo=modulos.id WHERE (modulos.URLCliente='" + pagina + "' AND modulosPermisos.idNivelUsuario='" + nivelUsuario + "' AND modulosPermisos.cliente='1') OR ( modulos.URLAdmin='" + pagina + "' AND modulosPermisos.idNivelUsuario='" + nivelUsuario + "' AND modulosPermisos.admin='1')";
            rsDatos = ConexionDB.ExecuteReader(strCommand);
            if (rsDatos.HasRows)
            {
                HttpContext.Current.Session["idModulo"] = rsDatos["idModulo"].ToString();
                accessGranted = true;
            }
            if (accessGranted)
            {
                //cargar librerias;
            }
            else
            {
                HttpContext.Current.Response.Redirect(redireccion);
            }

        }


        public static void RenewSession(dbConnector ConexionDB)
        {
            //string pagina, redireccion, strCommand, nivelUsuario;
            //bool accessGranted = false;
            HttpCookie recordar = HttpContext.Current.Request.Cookies["rememberMe"];
            if (recordar != null)
                if (Convert.ToBoolean(recordar.Value) && HttpContext.Current.Session["idUsuario"] == null)
                {

                    ValidateUser(HttpContext.Current.Request.Cookies["email"].Value.ToString(), HttpContext.Current.Request.Cookies["password"].Value.ToString(), Convert.ToBoolean(HttpContext.Current.Request.Cookies["rememberMe"].Value), ref ConexionDB);
                }
            //OdbcDataReader rsDatos;

            //pagina = HttpContext.Current.Request.ServerVariables["URL"].ToString();
            //HttpContext.Current.Session["accessDenied"] = pagina.ToString();
            //HttpContext.Current.Session[""] = HttpContext.Current.Request.ServerVariables["QUERY_STRING"];
            //redireccion = "/login.aspx";
            //if (Convert.ToInt32(HttpContext.Current.Request.QueryString["ajax"]) == 1)
            //{
            //    redireccion = redireccion + "?ajax=1&pagina=" + pagina;
            //}
            //else
            //    redireccion = redireccion + "?pagina=" + pagina;
            //if (HttpContext.Current.Session["nivelUsuario"] == null)
            //{
            //    HttpContext.Current.Session["nivelUsuario"] = "1";
            //    HttpContext.Current.Session["nivelPrecio"] = "1";
            //}
            //nivelUsuario = Convert.ToString(HttpContext.Current.Session["nivelUsuario"]);
            //strCommand = "SELECT 1,modulos.id as idModulo FROM modulosPermisos join modulos on modulosPermisos.idModulo=modulos.id WHERE (modulos.URLCliente='" + pagina + "' AND modulosPermisos.idNivelUsuario='" + nivelUsuario + "' AND modulosPermisos.cliente='1') OR ( modulos.URLAdmin='" + pagina + "' AND modulosPermisos.idNivelUsuario='" + nivelUsuario + "' AND modulosPermisos.admin='1')";
            //rsDatos = ConexionDBInterna.ExecuteReader(strCommand);
            //if (rsDatos.HasRows)
            //{
            //    HttpContext.Current.Session["idModulo"] = rsDatos["idModulo"].ToString();
            //    accessGranted = true;
            //}
            //if (accessGranted)
            //{
            //    //cargar librerias;
            //}
            //else
            //{
            //    HttpContext.Current.Response.Redirect(redireccion);
            //}

        }



        //private static void GetCurrentDomainInfo()
        //{
        //    dbConnector conn = new dbConnector();
        //    string _host;
        //    string _dominio = "";
        //    string _logotipo;
        //    string _slogan;
        //    string _estadisticas;
        //    string _keywords;
        //    string _description;
        //    int _idDominio;
        //    string _subdomain;
        //    host = HttpContext.Current.Request.Url.Host;
        //    MiWebSiteDomainCollection listaDominios = new MiWebSiteDomainCollection(conn);
        //    string dominioActualHost = "";
        //    foreach (MiWebSiteDomain dominioActual in listaDominios.DomainsList)
        //    {
        //        if (_host.Contains(dominioActual.dominio))
        //        {
        //            dominioActualHost = dominioActual.dominio;
        //            dominio = dominioActual.dominio;
        //            logotipo = dominioActual.logotipo;
        //            slogan = dominioActual.slogan;
        //            estadisticas = dominioActual.estadisticas;
        //            keywords = dominioActual.keywords;
        //            description = dominioActual.description;
        //            idDominio = dominioActual.id;
        //        }
        //    }

        //    HttpContext.Current.Response.Write("Datos de Dominio Cargados");
        //}

        public static bool ValidateUser(string email, string password, bool rememberMe, ref dbConnector ConexionDB)
        {

            MiWebSiteUser usuario = new MiWebSiteUser(email,ref ConexionDB);
            if (usuario != null)
            {
                if (password == usuario.password)
                {
                    //HttpContext.Current.Response.Write(usuario.activo);
                    if (true)
                    {

                        HttpContext.Current.Session["password"] = usuario.password;
                        HttpContext.Current.Session["idUsuario"] = usuario.id;
                        HttpContext.Current.Session["email"] = usuario.email;
                        HttpContext.Current.Session["nivelUsuario"] = usuario.nivelUsuario;
                        HttpContext.Current.Session["UserName"] = usuario.username;
                        HttpContext.Current.Session["LastLogin"] = DateTime.Now.ToString();
                        HttpContext.Current.Session["FullName"] = usuario.nombre + " " + usuario.apellidos;
                        //HttpContext.Current.Session["nivelPrecio"]=usuario.niv
                        if (rememberMe)
                        {
                            HttpCookie cookieEmail = new HttpCookie("email", usuario.email);
                            cookieEmail.Expires = DateTime.Now.AddDays(30);
                            HttpContext.Current.Response.Cookies.Add(cookieEmail);

                            HttpCookie cookiePassword = new HttpCookie("password", usuario.password);
                            cookiePassword.Expires = DateTime.Now.AddDays(30);
                            HttpContext.Current.Response.Cookies.Add(cookiePassword);

                            HttpCookie cookieIdUsuario = new HttpCookie("idUsuario", usuario.id.ToString());
                            cookieIdUsuario.Expires = DateTime.Now.AddDays(30);
                            HttpContext.Current.Response.Cookies.Add(cookieIdUsuario);

                            HttpCookie cookieUserName = new HttpCookie("UserName", usuario.username);
                            cookieUserName.Expires = DateTime.Now.AddDays(30);
                            HttpContext.Current.Response.Cookies.Add(cookieUserName);

                            HttpCookie cookieRememberMe = new HttpCookie("rememberMe", rememberMe.ToString());
                            cookieRememberMe.Expires = DateTime.Now.AddDays(30);
                            HttpContext.Current.Response.Cookies.Add(cookieRememberMe);

                            HttpCookie cookieNivelUsuario = new HttpCookie("nivelUsuario", usuario.nivelUsuario.ToString());
                            cookieNivelUsuario.Expires = DateTime.Now.AddDays(30);
                            HttpContext.Current.Response.Cookies.Add(cookieNivelUsuario);


                        }
                        //usuario.ultimoLogin = DateTime.Now;
                        //usuario.Save();
                        return true;
                    }


                }
                else
                    return false;
            }

            return false;
        }

        public static void LogOutUser()
        {
            HttpContext.Current.Session.Abandon();
            HttpContext.Current.Response.Cookies["email"].Expires = DateTime.Now.AddDays(-1);
            HttpContext.Current.Response.Cookies["password"].Expires = DateTime.Now.AddDays(-1);
            HttpContext.Current.Response.Cookies["idUsuario"].Expires = DateTime.Now.AddDays(-1);
            HttpContext.Current.Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(-1);
            HttpContext.Current.Response.Cookies["rememberMe"].Expires = DateTime.Now.AddDays(-1);
            HttpContext.Current.Response.Cookies["nivelUsuario"].Expires = DateTime.Now.AddDays(-1);
        }

        //public static string XMLFeed(string xmlUrl)
        //{
        //    StringBuilder salida = new StringBuilder();
        //    XmlDocument documento = new XmlDocument();
        //    documento.Load(xmlUrl);
        //    int contador = 0;
        //    foreach (XmlNode nodo in documento.GetElementsByTagName("item"))
        //    {
        //        salida.Append("<div style='float:none;'><div style='float:none; width:600px;'><img src='" + nodo.SelectSingleNode("image").InnerText + "' width='200' style='float:left; margin:4px;'><h3><a href='" + nodo.SelectSingleNode("link").InnerText + "'>" + nodo.SelectSingleNode("title").InnerText.ToString() + "</a></h3>");
        //        string descripcion = nodo.SelectSingleNode("description").InnerText.ToString();
        //        if (descripcion.Length > 200)
        //            salida.Append(descripcion.Substring(0, 200));
        //        else
        //            salida.Append(descripcion);
        //        salida.Append("</div></div>");
        //        contador++;
        //        if (contador > 10)
        //            return salida.ToString();
        //    }

        //    return salida.ToString();
        //}

        public static bool VerificarDominio(string dominio)
        {
            System.Net.HttpWebRequest req;
            System.Net.HttpWebResponse res;
            System.IO.StreamReader r;
            int pge;
            string url = "http://" + dominio;
            try
            {
                req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
                req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705)";
                res = (System.Net.HttpWebResponse)req.GetResponse();
                r = new System.IO.StreamReader(res.GetResponseStream());
                pge = r.Read();
                r.Close();
                res.Close();


                //if (pge == null)
                //    return true;
                //else
                return false;
            }
            catch (Exception ex)
            {
                return true;
            }
            finally
            {
                //if (ErrMSG.Text == "")
                //{
                //    ErrMSG.Text = "Domain is available";
                //}
            }

        }

        public static void NoCache()
        {
            HttpContext.Current.Response.AddHeader("Expires", " Mon, 26 Jul 1997 05:00:00 GMT");
            HttpContext.Current.Response.AddHeader("Last-Modified", DateTime.UtcNow.ToString());
            HttpContext.Current.Response.AddHeader("Cache-Control", " no-cache, must-revalidate");
            HttpContext.Current.Response.AddHeader("Pragma", "no-cache");
            HttpContext.Current.Response.AddHeader("Content-type", "text");
        }

        //public static void DisablePageCaching(System.Web.UI.Page page)
        //{

        //    page.Response.Cache.SetExpires(DateTime.Now.AddDays(-30));

        //    page.Response.Cache.SetCacheability(HttpCacheability.NoCache);

        //    page.Response.Cache.SetNoServerCaching();

        //    page.Response.Cache.SetNoStore();

        //}

        public static string RenderControl(Control ctrl)
        {
            StringBuilder sb = new StringBuilder();
            StringWriter tw = new StringWriter(sb);
            HtmlTextWriter hw = new HtmlTextWriter(tw);

            ctrl.RenderControl(hw);
            return sb.ToString();
        }

        public static void LoadIncludesWebSite(MiWebSitePage pagina)
        {
            pagina.StyleSheets.Add("/css/globalcss.css");
            pagina.StyleSheets.Add("/css/jquery-ui.css");
            pagina.Scripts.Add("/jquery/jquery.js");
            pagina.Scripts.Add("/jquery/jquery.droppy.js");
            pagina.Scripts.Add("/jquery/jquery.pngFix.js");
            pagina.Scripts.Add("/jquery/jquery.form.js");
            pagina.Scripts.Add("/jquery/Encoder.js");
            pagina.Scripts.Add("/jquery/jquery.validate.min.js");
            pagina.Scripts.Add("/jquery/jquery-ui.js");
            pagina.Scripts.Add("/jquery/jquery.example.js");
            pagina.Scripts.Add("/jquery/js.js");
            pagina.Scripts.Add("/jquery/jsWLM.js");
            pagina.Scripts.Add("/jquery/InitWebpage.js");

        }

        public static void LoadIncludesWebSiteAdmin(MiWebSitePage pagina)
        {
            pagina.StyleSheets.Add("/css/ajax-upload.css");
            pagina.StyleSheets.Add("/css/tipsy.css");            
            pagina.StyleSheets.Add("/css/jquery.fcbkcomplete.css");
            

            pagina.Scripts.Add("/fckeditor/fckeditor.js");
            pagina.Scripts.Add("/jquery/jquery.fckeditor.js");
            pagina.Scripts.Add("/jquery/jquery.ajaxupload.js");
            pagina.Scripts.Add("/jquery/jquery.fcbkcomplete.js");
            pagina.Scripts.Add("/jquery/jquery.tipsy.js");
            pagina.Scripts.Add("/jquery/admin.js");
            pagina.Scripts.Add("/jquery/Menuadmin.js");
            pagina.Scripts.Add("/jquery/jquery.uiupload.js");
        }
    }

    public class DomainLicence
    {
        public DomainLicence()
        {


        }

        public static string CheckLicence(string Domain)
        {
            SaltedHash demo = new SaltedHash();

            // We have a password, which will generate a Hash and Salt




            return (demo.CreateDomainHash(Domain));
        }
    }

    public static class GetUrl
    {
        public static string FetchURL(string url)
        {

            const int bufSizeMax = 65536; // max read buffer size conserves memory
            const int bufSizeMin = 8192; // min size prevents numerous small reads
            StringBuilder sb;

            // A WebException is thrown if HTTP request fails
            try
            {

                // Create an HttpWebRequest using WebRequest.Create (see .NET docs)!
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

                request.Method = WebRequestMethods.Http.Get;

                // Execute the request and obtain the response stream
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream responseStream = response.GetResponseStream();

                // Content-Length header is not trustable, but makes a good hint.
                // Responses longer than int size will throw an exception here!
                int length = (int)response.ContentLength;

                // Use Content-Length if between bufSizeMax and bufSizeMin
                int bufSize = bufSizeMin;
                if (length > bufSize)
                    bufSize = length > bufSizeMax ? bufSizeMax : length;

                // Allocate buffer and StringBuilder for reading response
                byte[] buf = new byte[bufSize];
                sb = new StringBuilder(bufSize);

                // Read response stream until end
                while ((length = responseStream.Read(buf, 0, buf.Length)) != 0)
                    sb.Append(Encoding.UTF8.GetString(buf, 0, length));

                return sb.ToString();

            }
            catch (Exception ex)
            {
                sb = new StringBuilder(ex.Message);
                return sb.ToString();
            }

        }
    }
}

